import struct
'''实现modbus中对int、float等格式数据的转换，传输'''
def ReadFloat(*args,reverse=False):
    for n,m in args:
        n,m = '%04x'%n,'%04x'%m
    if reverse:
        v = n + m
    else:
        v = m + n
    y_bytes = bytes.fromhex(v)
    y = struct.unpack('!f',y_bytes)[0]
    y = round(y,6)
    return y

def WriteFloat(value,reverse=False):
    y_bytes = struct.pack('!f',value)
    # y_hex = bytes.hex(y_bytes)
    y_hex = ''.join(['%02x' % i for i in y_bytes])
    n,m = y_hex[:-4],y_hex[-4:]
    n,m = int(n,16),int(m,16)
    if reverse:
        v = [n,m]
    else:
        v = [m,n]
    return v

def WriteFloats(values,reverse=False):
    '''将浮点数转换为2个双字节整数'''
    v = [0]*len(values)*2
    x = 0
    for value in values:
        y_bytes = struct.pack('!f',value)
        # y_hex = bytes.hex(y_bytes)
        y_hex = ''.join(['%02x' % i for i in y_bytes])
        n,m = y_hex[:-4],y_hex[-4:]
        n,m = int(n,16),int(m,16)
        if reverse:
            v[x] = n
            v[x+1] = m
        else:
             v[x] = m
             v[x+1] = n
        x+=2
    return v

def ReadDint(*args,reverse=False):
    for n,m in args:
        n,m = '%04x'%n,'%04x'%m
    if reverse:
        v = n + m
    else:
        v = m + n
    y_bytes = bytes.fromhex(v)
    y = struct.unpack('!i',y_bytes)[0]
    return y

def WriteDint(value,reverse=False):
    y_bytes = struct.pack('!i',value)
    # y_hex = bytes.hex(y_bytes)
    y_hex = ''.join(['%02x' % i for i in y_bytes])
    n,m = y_hex[:-4],y_hex[-4:]
    n,m = int(n,16),int(m,16)
    if reverse:
        v = [n,m]
    else:
        v = [m,n]
    return v

if __name__ == "__main__":
    print(ReadFloat((15729,16458)))
    print(WriteFloat(1.1))
    print(ReadDint((1734,6970)))
    print(WriteDint(456787654))
